package com.hhq.common.annotation;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.hhq.common.domain.vo.CommonResultVO;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>Description: 日志打印切面 </p>
 *
 * @author : xiaodong.yang
 * @date : 2023/10/13 15:47
 */
@Aspect
@Component
@Slf4j
public class ApiLogAspect {
    /**
     * @param point
     * @param apiLog
     * @return
     * @throws Throwable
     */
    @Around("@annotation(apiLog)")
    public Object around(ProceedingJoinPoint point, ApiLog apiLog) throws Throwable {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        // 打印请求内容
        log.info("=========================请求内容===========================");
        log.info("请求地址:{}", request.getRequestURL().toString());
        log.info("请求方式:{}", request.getMethod());
        log.info("请求类方法:{}", point.getSignature());
        log.info("请求类方法参数:{}", JSONUtil.toJsonStr(point.getArgs()));
        // 发送异步日志事件
        long beginTime = System.currentTimeMillis();
        try {
            //执行方法
            Object result = point.proceed();
            //执行时长(毫秒)
            long responseTime = System.currentTimeMillis() - beginTime;
            setResponseTime(result, responseTime);
            log.info("请求接口返回值:{}", JSONUtil.toJsonStr(result));
            log.info("请求接口消耗时间:{}毫秒", responseTime);
            log.info("==========================================================");
            return result;
        } catch (Exception e) {
            //执行时长(毫秒)
            long responseTime = System.currentTimeMillis() - beginTime;
            log.error("请求接口异常，异常信息:{}", e.getMessage());
            log.info("请求接口消耗时间:{}毫秒", responseTime);
            log.info("==========================================================");
            throw e;
        }
    }

    /**
     * 设置接口响应时间
     *
     * @param result
     * @param responseTime
     */
    private void setResponseTime(Object result, long responseTime) {
        if (result instanceof CommonResultVO) {
            CommonResultVO<?> commonResult = (CommonResultVO<?>) result;
            commonResult.setResponseTime(responseTime);
        }
    }
}
